package com.wantup.demo01;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/26 17:55
 * <p>
 * 读写锁
 */
public class TestReadWriteLock {

    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();


        new Thread(new Runnable() {
            @Override
            public void run() {

                demo.set((int) (Math.random() * 101));

            }
        }, "写").start();


        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.get();
                }
            }, "读").start();
        }


    }

}

class ReadWriteLockDemo {

    private  int number;
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //读
    public void get() {
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + " : " + number);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    //写
    public void set(int number) {
        try {
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName());
            this.number = number;
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

}



